package com.xm.linxiaogang.base.fragment

import androidx.annotation.IdRes
import androidx.fragment.app.Fragment
import com.trello.rxlifecycle3.components.support.RxFragment

abstract class LibBaseFragment : RxFragment() {

    /**
     * 添加 fragment
     *
     * @param idRes    容器ID
     * @param fragment 待添加的 fragment
     */
    fun addFragment(@IdRes idRes: Int, fragment: RxFragment) {
        val ft = requireActivity().supportFragmentManager.beginTransaction()
        ft.add(idRes, fragment)
        ft.commit()
    }

    /**
     * 替换 fragment
     *
     * @param idRes    容器ID
     * @param fragment 待替换的 fragment
     */
    fun replaceFragment(@IdRes idRes: Int, fragment: RxFragment?) {
        val ft = requireActivity().supportFragmentManager.beginTransaction()
        ft.replace(idRes, fragment!!)
        ft.commit()
    }

    /**
     * 隐藏 fragment
     *
     * @param fragment
     */
    fun hideFragment(fragment: RxFragment) {
        val ft = requireActivity().supportFragmentManager.beginTransaction()
        ft.hide(fragment)
        ft.commit()
    }

    /**
     * 显示 fragment
     *
     * @param fragment
     */
    fun showFragment(fragment: RxFragment) {
        val ft = requireActivity().supportFragmentManager.beginTransaction()
        ft.show(fragment)
        ft.commit()
    }

    /**
     * 设置当前Fragment
     *
     * @param id
     * @param fragment
     */
    fun setCurrentFragment(id: Int, fragment: Fragment) {
        val fragments = requireActivity().supportFragmentManager.fragments
        val fragmentTransaction = requireActivity().supportFragmentManager.beginTransaction()
        if (!fragment.isAdded) {
            fragmentTransaction.add(id, fragment, fragment.toString())
        }
        for (i in fragments.indices) {
            val f = fragments[i]
            if (f.tag != fragment.id.toString()) {
                fragmentTransaction.hide(f)
            }
        }
        fragmentTransaction.show(fragment)
        fragmentTransaction.commitAllowingStateLoss()
        requireActivity().supportFragmentManager.executePendingTransactions()
    }
}